﻿using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Globalization;
using HF.Framework.DataClientDBAgent;
using HF.WorkFlow.DataContract;
using HF.Framework.SqlDataContract;

namespace HF.Framework.Log
{
    public class ErrorLogData
    {
            #region  私有字段
        private SqlDataItem sqlDataItem = new SqlDataItem();
        private string[] fieldList = { "Logid","LogContent","LogUserContent","LogType","LogSatus","WorkTaskInstanceId","LogDatetime"};
        private string tableName = "HF_ErrorLogs";
        private string keyField = "Logid";
        private string sqlString = "";

        #endregion

        #region  私有方法
        private void setParameter(ErrorLogEntity entity)
        {
            sqlDataItem.ParameterList.Clear();
            sqlDataItem.AppendParameter("@Logid", entity.LogId, typeof(string));
            sqlDataItem.AppendParameter("@LogContent", entity.LogContent, typeof(string));
            sqlDataItem.AppendParameter("@LogUserContent", entity.LogUserContent, typeof(string));
            sqlDataItem.AppendParameter("@LogType", entity.LogType, typeof(string));
            sqlDataItem.AppendParameter("@LogSatus", entity.LogSatus, typeof(string));
            sqlDataItem.AppendParameter("@WorkTaskInstanceId", entity.WorkTaskInstanceId, typeof(string));
            sqlDataItem.AppendParameter("@LogDatetime", entity.LogDatetime, typeof(DateTime));
        }

        private void setInsertSql()
        {
            string tmpValueList = "";
            string tmpFieldName = "";
            sqlString = "insert into " + tableName + "(";
            int tmpInt = this.fieldList.Length;
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + ", ";
                tmpValueList = tmpValueList + "@" + tmpFieldName + ",";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName;
            tmpValueList = tmpValueList + "@" + tmpFieldName;
            this.sqlString = sqlString + ")values(" + tmpValueList + ")";
            sqlDataItem.CommandText = sqlString;
        }

        private void setUpdateSql()
        {
            string tmpFieldName = "";
            int tmpInt = this.fieldList.Length;
            sqlString = "update " + tableName + " set ";
            for (int i = 0; i < tmpInt - 1; i++)
            {
                tmpFieldName = fieldList[i].ToString();
                sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName + ", ";
            }
            tmpFieldName = this.fieldList[tmpInt - 1].ToString();
            sqlString = sqlString + tmpFieldName + " = @" + tmpFieldName;
            sqlString = sqlString + " where " + keyField + "=@" + this.keyField;
            sqlDataItem.CommandText = sqlString;
        }

    

        #endregion

        #region  构造函数
        public ErrorLogData()
        { }
        public static ErrorLogData GetInstance()
        {
            return new ErrorLogData();
        }
        #endregion

        #region  公有方法
        #region  基本方法
        /// <summary>
        /// 增加
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Insert(ErrorLogEntity entity)
        {
            try
            {
                setInsertSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="entity">数据实体</param>
        /// <returns>影响的记录条数</returns>
        public int Update(ErrorLogEntity entity)
        {
            try
            {
                setUpdateSql();//设定insert语句
                setParameter(entity);//设定参数
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteNonQuery(sqlDataItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string logId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            SqlDataItem sqlItem = new SqlDataItem();
            sqlItem.CommandText = tmpSql;
            sqlItem.AppendParameter("@" + keyField, logId);
            ClientDBAgent agent = new ClientDBAgent();
            return agent.RecordExists(sqlItem);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="logId">主键Id</param>
        /// <returns>影响的记录条数</returns>
        public void Delete(string logId)
        {
            try
            {
                string tmpSql = "delete from " + tableName + " where  " + keyField + "=@" + keyField;
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, logId);
                ClientDBAgent agent = new ClientDBAgent();
                agent.ExecuteNonQuery(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取一条数据记录
        /// </summary>
        /// <param name="LogId">主键Id</param>
        /// <returns>DataTable</returns>
        public DataTable GetLogTable(string logId)
        {
            string tmpSql = "select * from " + tableName + " where " + keyField + "=@" + keyField;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@" + keyField, logId);
                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        ///// <summary>
        ///// 获取一个数据实体
        ///// </summary>
        ///// <param name="logId">主键Id</param>
        ///// <returns>DataTable</returns>
        //public ErrorLogEntity GetLogEntity(string logId)
        //{
        //    DataTable dt = GetLogTable(logId);
        //    if (dt != null && dt.Rows.Count > 0)
        //    {
        //        return GetLogEntity(dt.Rows[0]);
        //    }
        //    return null;
        //}
        public DataTable GetLogTable(DateTime startTime, DateTime endTime)
        {
            string tmpSql = "select * from  HF_ErrorLogs where LogDatetime between @startTime and @endTime order by LogDatetime desc";
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = tmpSql;
                sqlItem.AppendParameter("@startTime", startTime, typeof(DateTime));
                sqlItem.AppendParameter("@endTime", endTime, typeof(DateTime));

                ClientDBAgent agent = new ClientDBAgent();
                return agent.ExecuteDataTable(sqlItem);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region  扩展方法
        /// 获得当前日期,yyyymmdd
        /// </summary>
        /// <returns></returns>
        public static string GetNowDate()
        {
            return DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
        }
        public static string GetLogId()
        {
            Int64 result = 0;
            try
            {
                SqlDataItem sqlItem = new SqlDataItem();
                sqlItem.CommandText = "HF_CreatAutoCodePro";
                sqlItem.CommandType = CommandType.StoredProcedure.ToString();
                sqlItem.AppendParameter("@Auto_Type", "SysLog");
                ClientDBAgent agent = new ClientDBAgent();
                result=Convert.ToInt64(agent.ExecuteScalar(sqlItem));
                return GetNowDate()+result.ToString("00000000");

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        //此处添加扩展方法
        public static void WriteLog(string typeDll,string typeName,string getMethod,string getMethods,string content, string LogUserContent, string LogSatus, string logType,string WorkTaskInstanceId)
        {
            try
            {
                ClientDBAgent agent = new ClientDBAgent();
                StringBuilder logContent = new StringBuilder();
                logContent.AppendLine("时间:" + agent.GetDBDateTime());
                logContent.AppendLine("DLL:" + typeDll);
                logContent.AppendLine("类名:" + typeName);
                logContent.AppendLine("方法:" + getMethod+"->"+getMethods);
                logContent.AppendLine("内容:" + content);

                ErrorLogEntity entity = new ErrorLogEntity();
                entity.LogId = GetLogId();
                entity.LogContent = logContent.ToString();
                entity.LogUserContent = LogUserContent;
                entity.LogSatus = LogSatus;
                entity.LogType = logType;
                entity.WorkTaskInstanceId = WorkTaskInstanceId;
                entity.LogDatetime = Convert.ToDateTime(agent.GetDBDateTime());//取服务器时间
                ErrorLogData.GetInstance().Insert(entity);
           
            }
            catch (Exception ex)
            {
                
                throw ex;
            }
        }
    
        ///// <summary>
        /////  写应用程序服务日志
        ///// </summary>
        ///// <param name="Content">日志内容</param>
        ///// <param name="msgtype">日志类型</param>
        //public static void WriteAppServerLog(string Content, string msgtype)
        //{
        //    string isDebugHF = System.Configuration.ConfigurationSettings.AppSettings["IsDebug"];
        //    if (isDebugHF.ToLower() == "true")
        //    {
        //        string sqlStr = "insert into HF_AppServerLog(Content,msgtype)values(@Content,@msgtype)";
        //        SqlDataItem sqlItem = new SqlDataItem();
        //        sqlItem.AppendParameter("@Content", Content);
        //        sqlItem.AppendParameter("@msgtype", msgtype);

        //        sqlItem.CommandText = sqlStr;
        //        ClientDBAgent agent = new ClientDBAgent();
        //        agent.ExecuteNonQuery(sqlItem);
        //    }
        //}
        //public List<ErrorLogEntity> GetLogEntitys(DateTime startTime, DateTime endTime)
        //{
        //    List<ErrorLogEntity> result = new List<ErrorLogEntity>();
        //    DataTable dt = GetLogTable(startTime, endTime);
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        ErrorLogEntity entity = GetLogEntity(dr);
        //        result.Add(entity);
        //    }
        //    return result;
        //}
        #endregion
        #endregion
    }
}
